#!groovy
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

/**
 * 默认tag
 * @return
 */
@NonCPS
def getDefaultTag() {
    LocalDateTime localDateTime = LocalDateTime.now()
    localDateTime.format(DateTimeFormatter.ofPattern('yyyyMMddHHmmss', Locale.CHINESE))
}

/**
 * maven构建脚本
 */
def call(body) {
    def config = [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = config
    body()

    assert config.name: 'name不能为空'

    def needHost = config.needHost ?: 'false'
    def imageName = params.IMAGE_NAME ?: config.name
    def deployEnv = params.DEPLOY_ENV ?: 'dev'
    def type = config.type ?: 'maven'
    def coverage = config.coverage ?: '10'

    def imageTag = params.INAGE_TAG ?: getDefaultTag()
    def baseImage = params.BASE_IMAGE ?: env.BASE_IMAGE
    assert baseImage: 'baseImage不能为空'

    node {
        if (params.BUILD_MODE != 'DEPLOY_ONLY') {
            stage('代码检出') {
                echo '拉取代码'
                checkout scm
            }
        }

        if (params.BUILD_MODE != 'DEPLOY_ONLY') {
            switch (type) {
                case 'maven':
                    withMaven(jdk: 'java', maven: 'maven3.3.9', options: [jacocoPublisher(disabled: true)]) {
                        mavenProject(imageName, imageTag, coverage)
                    }
                    break
                default:
                    error '目前仅支持maven项目构建，构建失败'
                    return
            }
        }

        if (params.BUILD_MODE != 'BUILD_ONLY' && params.DEPLOY_TO == 'kubernetes') {
            if (params.BUILD_MODE == 'DEPLOY_ONLY') {
                assert params.IMAGE_TAG: 'IMAGE_TAG不能为空'
            }

            timestamps {
                withEnv(["PATH=/usr/local/bin:${PATH}, DEPLOY_ENV=${deployEnv}"]) {
                    deployKubernetes(config.name, "${imageName}:${imageTag}", needHost)
                }
            }
        }

        stage('Completed') {
            echo 'Deleting ...'
            sh returnStatus: true, script: 'docker rmi -f $(docker images | grep ' + imageName + ' | awk \'{print $3}\')'
            cleanWs()
        }
    }
}